<template>
  <div class="in_data">
    <a-card>
      <!-- 创建按钮 -->
      <div class="role_title">
        <span>数据源列表</span>
        <a-button type="primary" class="set_up" @click="onSetUpData" icon="plus" v-action:add="'datasource'">新建</a-button>
      </div>
      <!-- 表格 -->
      <a-table
        :columns="columns"
        :data-source="datasourceList"
        :pagination="currentConfig"
        @change="onTableHandle"
        rowKey="id"
        style="margin-top:24px;"
        :scroll="{x: true}"
        :loading="table_loading"
      >
        <span slot="action" slot-scope="row">
          <a v-action:edit="'datasource'" @click="onUpdateData(row)">编辑</a>
          <a-divider  type="vertical" style="opacity: 0;" />
          <a v-action:delete="'datasource'" @click="onDeleteData(row)">删除</a>
        </span>
      </a-table>
    </a-card>
    <!-- 抽屉 -->
    <a-drawer
      :title="title"
      placement="right"
      :maskClosable="false"
      :visible="drawer"
      width="50%"
      @close="onClose"
    >
      <!-- 表单 -->
      <a-form-model
        ref="ruleForm"
        :model="form.data"
        :rules="rules"
        :label-col="{ xl: {span: 4 }, lg: { span: 5 } }"
        :wrapper-col="{ xl:{span: 20}, lg: { span: 19 } }"
      >
        <!-- 数据源名称 -->
        <a-form-model-item label="数据源名称" prop="name">
          <a-input v-model="form.data.name" placeholder="请输入数据源名称"/>
        </a-form-model-item>
        <!-- 数据源类型 -->
        <a-form-model-item label="数据源类型" prop="type">
          <span v-if="form.data.id">
            {{form.data.type == 1 ? 'JDBC数据源' : '行为分析平台'}}
          </span>
          <a-select v-model="form.data.type" placeholder="请输入数据源类型" v-else @change="onSelectChange">
            <a-select-option :value="0">
              行为分析平台
            </a-select-option>
            <a-select-option :value="1">
              JDBC数据源
            </a-select-option>
          </a-select>
        </a-form-model-item>
        <a-form-model-item label="数据库类型" prop="dbType" v-if="form.data.type === 1">
          <a-select v-model="form.data.dbType" placeholder="请选择数据库类型" @change="onChangeDatabase">
            <a-select-option v-for="item in db_type" :id="item.id" :key="item.id" :value="item.name">
              {{item.name}}
            </a-select-option>
          </a-select>
        </a-form-model-item>
        <!-- 内置 -->
        <a-form-model-item v-if="!form.data.type" label="URL" prop="analysisUrl">
          <a-input v-model="form.data.analysisUrl" placeholder="请输入url"/>
        </a-form-model-item>
        <a-form-model-item v-if="!form.data.type" label="项目ID" prop="analysisProject">
          <a-input v-model="form.data.analysisProject" placeholder="请输入项目id"/>
        </a-form-model-item>
        <!-- JDBC -->
        <a-form-model-item v-if="form.data.type" label="URL" prop="jdbcUrl">
          <a-input v-model="form.data.jdbcUrl" placeholder="请输入url"/>
        </a-form-model-item>
        <a-form-model-item v-if="form.data.type" label="用户名" prop="jdbcUsername">
          <a-input v-model="form.data.jdbcUsername" placeholder="请输入用户名"/>
        </a-form-model-item>
        <a-form-model-item v-if="form.data.type" label="密码" prop="jdbcPassword">
          <a-input-password v-model="form.data.jdbcPassword" placeholder="请输入密码"/>
        </a-form-model-item>
        <!-- 说明 -->
        <a-form-model-item label="说明" prop="remark">
          <a-input v-model="form.data.remark" type="textarea" placeholder="写一段说明" />
        </a-form-model-item>
      </a-form-model>
      <div class="data-action">
        <a-divider />
        <a-button class="save_button" type="primary" @click="onSubmit" :loading="form.loadingBtn" :disabled="form.statusBtn">
          保存
        </a-button>
        <a-button class="cancal_button" @click="drawer = false">
          取消
        </a-button>
      </div>
    </a-drawer>
  </div>
</template>

<script>
import { mapActions, mapMutations, mapState } from 'vuex';
import { baseMixin } from '@/store/app-mixin';
const columns = [
        {
          title: '数据源名称',
          dataIndex: 'name',
          sorter: true
        },
        {
          title: '数据源类型',
          dataIndex: 'type',
          sorter: true
        },
        {
          title: '数据库类型',
          dataIndex: 'dbType',
          sorter: true
        },
        {
          title: '说明',
          dataIndex: 'remark'
        },
        {
          title: '创建时间',
          dataIndex: 'createdAt',
          sorter: true
        },
        {
          title: '更新时间',
          dataIndex: 'updatedAt',
          sorter: true
        },
        {
          title: '操作',
          fixed: 'right',
          width: 120,
          scopedSlots: { customRender: 'action' },
        }
      ];

const db_type = [
  {
    id: "1",
    name: "mysql"
  },
  {
    id: "2",
    name: "impala"
  },
  {
    id: "3",
    name: "clickhouse"
  },
  {
    id: "4",
    name: "elasticsearch"
  },
  {
    id: "5",
    name: "达梦"
  },
];

const db_schema = {
  "1": "jdbc:mysql://",
  "2": "jdbc:hive2://",
  "3": "jdbc:clickhouse://",
  "4": "jdbc:es://",
  "5": "jdbc:dm://"
}

  export default {
    name: 'InData',
    data () {
      return {
        columns,
        db_type,
        drawer: false,
        title: '创建数据源',
        table_loading: false,
        form: {
          loadingBtn: false,
          statusBtn: false,
          data: {
            type: 1,
            dbType: null,
            jdbcUrl: null
          }
        },
        rules: {
          name: [
            {
              required: true,
              trigger: 'blur',
              message: '请输入数据源名称'
            },
            {
              max: 100,
              trigger: 'blur',
              message: '最大长度限制为100个字符'
            }
          ],
          analysisUrl: [
            {
              required: true,
              trigger: 'blur',
              message: '请输入报表平台分析服务URL'
            },
            {
              max: 255,
              trigger: 'blur',
              message: '最大长度限制为255个字符'
            }
          ],
          analysisProject: [
            {
              required: true,
              trigger: 'blur',
              message: '请输入项目ID'
            },
            {
              max: 100,
              trigger: 'blur',
              message: '最大长度限制为100个字符'
            }
          ],
          jdbcUrl: [
            {
              required: true,
              trigger: 'blur',
              message: '请输入URL'
            },
            {
              max: 255,
              trigger: 'blur',
              message: '最大长度限制为255个字符'
            }
          ],
          remark: [
            {
              max: 255,
              trigger: 'blur',
              message: '最大长度限制为255个字符'
            }
          ]
        },
      }
    },
    watch: {
      // 关闭抽屉清空表单
      drawer (val) {
        if (!val) {
          this.form.data = { type: 0 }
          this.$refs.ruleForm && this.$refs.ruleForm.clearValidate()
        }
      },
      form: {
        handler (val) {
          if (val.data.type) {
            let commonRules = {...this.rules}
            let rules = {
              name:[{required: true,trigger: 'blur',message: '请输入数据源名称'}, {max: 100,trigger:'blur',message:'最大长度限制为100个字符'}],
              analysisUrl: [{ required: true, trigger: 'blur',message: '请输入报表平台分析服务URL' }, {max: 255,trigger: 'blur',message: '最大长度限制为255个字符'}],
              analysisProject: [{required: true,trigger: 'blur',message: '请输入项目ID'}, {max: 100,trigger: 'blur',message: '最大长度限制为100个字符'}],
              jdbcUsername: [{required: true,trigger: 'blur',message: '请输入用户名'}, {max: 100,trigger: 'blur',message: '最大长度限制为100个字符'}],
              jdbcPassword: [{required:true,trigger: 'blur',message: '请输入密码'}, {max: 100,trigger: 'blur',message: '最大长度限制为100个字符' }],
              jdbcUrl: [{required: true,trigger: 'blur',message: '请输入URL' }, {max: 255,trigger: 'blur',message: '最大长度限制为255个字符' }],
              remark: [{max: 255,trigger: 'blur',message: '最大长度限制为255个字符' }],
              dbType:[{required: true,trigger: 'blur',message: '请选择数据库类型'}]
            }
            this.rules = val.data.type == 1 ? rules : commonRules
          }else {
            val.data.dbType = null
          }
        },
        deep: true
      }
    },
    mixins: [baseMixin],
    computed: {
      ...mapState('dataManage',['dataList', 'currentConfig']),
      datasourceList () {
        return this.dataList.map(data => {
          return {...data, type: data.type==1 ? 'JDBC数据源' : '行为分析平台'}
        })
      }
    },
    mounted () {
      this.onLoadDataConfig()
    },
    methods: {
      ...mapMutations('dataManage', ['SET_CURRENT', 'SET_PAGES', 'SET_ORDER']),
      ...mapActions('dataManage', ['getDSNList', 'addDSNList', 'updateDSNList', 'getUpdateDSNList', 'deleteDSNList']),
      // 保存
      onSubmit () {
        this.$refs.ruleForm.validate(valid => {
          if (valid) {
            if (this.form.data.type == 0) {
              this.form.data.jdbcUrl = null
              this.form.data.jdbcUsername = null
              this.form.data.jdbcPassword = null
            } else if(this.form.data.type == 1){
              this.form.data.analysisUrl = null
              this.form.data.analysisProject = null
            }
            this.form.statusBtn = true
            this.form.loadingBtn = true
            if (this.form.data.id) {
              this.updateDSNList({...this.form.data})
                .then((res) =>  {
                  this.drawer = false
                  this.$message.success('修改数据源成功')
                  this.getDSNList()
                })
                .catch(err => this.$message.error('修改数据源失败，原因：' + err.msg + '！'))
                .finally(() => {
                  this.form.loadingBtn = false
                  this.form.statusBtn = false
                })
            } else {
              this.addDSNList({...this.form.data})
                .then((res) => {
                  this.drawer = false
                  this.$message.success('创建数据源成功')
                  this.getDSNList()
                })
                .catch(err => this.$message.error('创建数据源失败，原因：' + err.msg + '！'))
                .finally(() => {
                  this.form.loadingBtn = false
                  this.form.statusBtn = false
                })
            }
          } else {
            setTimeout(()=>{
              this.form.loadingBtn = false
              this.form.statusBtn = false
              return false
            },1500)
          }
        })
      },
      // 创建
      onSetUpData () {
        this.drawer = true
        this.title = '创建数据源'
      },
      onSelectChange (val) {
        this.form = {
          loadingBtn: false,
          statusBtn: false,
          data: {
            type: val,
            dbType: null,
            jdbcUrl: null
          }
        }
        this.$refs.ruleForm && this.$refs.ruleForm.clearValidate()
      },
      onChangeDatabase (val,item){
        if (!this.form.data.id){
          this.form.data.jdbcUrl = typeof db_schema[item.key] === "string" ? new String(db_schema[item.key]):"";
        }
      },
      // 关闭抽屉
      onClose () {
        this.$confirm({
          title: '提示',
          content: '关闭后数据会丢失，确定关闭吗？',
          okText: '确定',
          cancelText: '取消',
          onOk: () => {
            this.drawer = false
          },
          onCancel: () => {},
        })
      },
      order_way (order) {
        if (order == 'ascend') {
          return 'asc'
        } else if(order == 'descend') {
          return 'desc'
        } else {
          return ''
        }
      },
      // 分页-每页条数
      onTableHandle (page, filters, {field, order}) {
        const orderObj = {
          order: this.order_way(order),
          orderBy: field || ''
        }
        this.SET_CURRENT(page.current)
        this.SET_PAGES(page.pageSize)
        this.SET_ORDER({...orderObj})
        this.getDSNList()
      },
      // 获取修改行
      onUpdateData (row) {
        this.title='修改数据源'
        this.drawer = true
        this.getUpdateDSNList(row.id)
          .then((res) => {
            this.form.data = {...res.data}
          })
          .catch((err) => this.$message.error('获取修改数据源信息失败，原因：'+err.msg+'！'))
      },
      // 获取删除行
      onDeleteData (row) {
        this.$confirm({
          title: '删除提示',
          content: '删除数据源信息无法恢复，您确定要继续吗？',
          okText: '确定',
          cancelText: '取消',
          onOk: () => {
            this.deleteDSNList(row.id)
              .then(()=> {
                this.$message.success('数据源删除成功')
                this.getDSNList()
              })
              .catch((err) => this.$message.error('数据源删除失败，原因：'+err.msg+'！'))
          },
          onCancel: () => {},
        })
      },
      // 初始化加载页面数据
      onLoadDataConfig () {
        this.table_loading = true;
        this.getDSNList()
          .then(res =>{})
          .catch(err =>{
            if (err.code == 401) {
              this.err401(err)
              return
            }
            this.$message.error('获取数据源列表失败，原因：' + err.msg + '！')
          })
          .finally(res =>{
            this.table_loading = false;
          })
      }
    }
  }
</script>

<style scoped>
.in_data{
  width: 100%;
  height: 100%;
}
.set_up{
  float: right;
}

.ant-drawer>>>.ant-drawer-body{
  height: calc(100% - 55px);
  display: flex;
  flex-direction: column;
  justify-content: space-between;
}

.ant-form{
  height: 100%;
  display: flex;
  flex-direction: column;
  overflow: auto;
  margin-top: 12px;
}

.submit_style{
  margin-bottom: 0;
  flex: 1;
}

.submit_style>>>.ant-col.ant-col-18.ant-form-item-control-wrapper{
  width: 100%;
  height: 100%;
}

.submit_style>>>.ant-form-item-control{
  display: flex;
  height: 100%;
  align-items: flex-end;
}

.submit_style>>>span.ant-form-item-children{
  width: 100%;
}

.save_button,
.cancal_button {
  float: right;
}

.cancal_button {
  margin-right: 15px;
}

.role_title{
  display: flex;
  justify-content: space-between;
}


.role_title span {
  display: block;
  float: left;
  margin-bottom: 0;
  padding-right: 12px;
  color: rgba(0,0,0,.85);
  font-weight: 500;
  font-size: 16px;
  line-height: 32px;
}

.ant-table-wrapper>>>td.ant-table-row-cell-break-word {
  padding: 10px;
}

.in_data>>>ul.ant-pagination.ant-table-pagination {
  width: 100%;
  display: flex;
}

.in_data>>>ul.ant-pagination.ant-table-pagination>li.ant-pagination-total-text {
  font-size: 14px;
  color: #999;
  flex: 1;
  text-indent: 10px;
}

.data-action .ant-divider-horizontal {
  margin: 12px 0;
}

.data-action {
  height: 60px;
}


</style>

<style>
.ant-drawer-body {
  padding: 12px 24px;
}
</style>
